package com.andaily.web.controller.validator;

import com.andaily.domain.dto.user.UserFormDTO;
import com.andaily.domain.shared.MatchUtils;
import com.andaily.infrastructure.support.LogHelper;
import com.andaily.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

/**
 * @author Shengzhao Li
 */
public class UserFormValidator implements Validator {

    private static LogHelper log = LogHelper.create(UserFormValidator.class);

    private UserService userService;

    @Override
    public boolean supports(Class<?> clazz) {
        return UserFormDTO.class.equals(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        UserFormDTO userFormDTO = (UserFormDTO) target;

        validateCellPhone(errors, userFormDTO);
        validatePassword(errors, userFormDTO);
    }

    private void validatePassword(Errors errors, UserFormDTO userFormDTO) {
        String oldPassword = userFormDTO.getOldPassword();
        String newPassword = userFormDTO.getNewPassword();
        if (StringUtils.isEmpty(oldPassword)) {
            log.debug("Ignore valid password");
            return;
        }
        if (StringUtils.isEmpty(oldPassword)) {
            errors.rejectValue("oldPassword", null, "旧密码为空");
        } else {
            //verify oldPassword is right or not
            boolean result = userService.checkCurrentUserPassword(oldPassword);
            if (!result) {
                errors.rejectValue("oldPassword", null, "旧密码不正确");
            }
        }

        if (newPassword.length() < 8) {
            errors.rejectValue("newPassword", null, "密码至少8位");
        }
        String confirmPassword = userFormDTO.getConfirmPassword();
        if (StringUtils.isEmpty(confirmPassword)) {
            errors.rejectValue("confirmPassword", null, "不能为空");
        } else {
            if (!confirmPassword.equals(newPassword)) {
                errors.rejectValue("confirmPassword", null, "与新密码不一致");
            }
        }


    }

    private void validateCellPhone(Errors errors, UserFormDTO userFormDTO) {
        String cellPhone = userFormDTO.getCellPhone();
        if (StringUtils.isEmpty(cellPhone)) {
            //empty is available
            return;
        }
        boolean isNumber = MatchUtils.isPositiveNumber(cellPhone);
        if (!isNumber) {
            errors.rejectValue("cellPhone", null, "手机必须是数字");
            return;
        }
        if (cellPhone.equals(userFormDTO.getOldCellPhone())) {
            return;
        }
        //check unique
        boolean unique = userService.uniqueCellphone(cellPhone);
        if (!unique) {
            errors.rejectValue("cellPhone", null, "该手机号码已经存在");
        }

    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }
}
